package pool;

import com.google.common.collect.Lists;
import org.junit.Test;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class NewObjectTest {

  @Test
  //测试一百万个对象，需要多少内存
  public void test1() {

    long l = Runtime.getRuntime().totalMemory();
    System.out.println(l);

    List<IndexDoc> indexDocs = new ArrayList<>();

    //100w = 616 000 000 b   600m  一个对象差不多有 616 b
    //500w = 3080 000 000    3g
    for (int i = 0; i < 1000000; i++) {
      indexDocs.add(new IndexDoc());
    }

    System.out.println(l / (1024.0 * 1024));

    double free = (Runtime.getRuntime().freeMemory());
    double used = (l - free) / (1024.0 * 1024);
    System.out.println(used);

    while (true) {
      try {
        Thread.sleep(1000);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }


  }


  @Test
  public void test2() {
    //
    ExecutorService executorService = Executors.newFixedThreadPool(200);

    long l = System.currentTimeMillis();

    while (true) {
      try {
        //600次/min
        Thread.sleep(100);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }

      Thread thread = new Thread(new Runnable() {
        @Override
        public void run() {

          //模拟用户请求
          new NewObjectTest().request();
        }
      });
      executorService.submit(thread);
    }
  }

  //每次请求创建 3w 个index
  public void request() {
    long l = System.currentTimeMillis();
    List<IndexDoc> list = Lists.newArrayList();
    for (int i = 0; i < 30000; i++) {
      list.add(new IndexDoc());
    }
    System.out.println(Thread.currentThread().getName() + "cost:" + (System.currentTimeMillis() - l));
  }

}
